package com.spring.security;

import com.spring.security.properties.SecurityConstants;
import com.spring.security.properties.SecurityProperties;
import com.spring.security.support.SimpleResponse;
import com.spring.security.support.SocialUsrInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class BrowserSecurityController {
    // 封装了引发跳转请求的工具类，从session中获取
    private RequestCache requestCache = new HttpSessionRequestCache();

    // spring的工具类：封装了所有跳转行为策略类
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 需要身份认证时跳转到这里
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requirAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        // 如果有引发认证的请求
        // spring 在跳转前应该会把信息存放在某个地方？
        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            System.out.println("引发跳转的请求：" + targetUrl);
            // 如果是html请求，则跳转到登录页
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        // 否则都返回需要认证的json串
        return new SimpleResponse("访问的服务需要身份认证!");
    }

    /**
     * 读取用户springSocial资料
     *
     * @return
     */
    @GetMapping("/social/user")
    public SocialUsrInfo getSocialUsrInfo(HttpServletRequest request) {
        SocialUsrInfo socialUsrInfo = new SocialUsrInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        socialUsrInfo.setProviderId(connection.getKey().getProviderId());
        socialUsrInfo.setProviderUserId(connection.getKey().getProviderUserId());
        socialUsrInfo.setNickname(connection.getDisplayName());
        socialUsrInfo.setHeadimg(connection.getImageUrl());
        return socialUsrInfo;
    }


}
